Skip to content

keyboard chord support, split up/down/left/right, and clear block#1957

Merged
sawka merged 12 commits intomainfrom
sawka/wavespace-lite
Feb 14, 2025
Merged

keyboard chord support, split up/down/left/right, and clear block#1957
sawka merged 12 commits intomainfrom
sawka/wavespace-lite

Conversation

@sawka
Copy link
Member

@sawka sawka commented Feb 13, 2025

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

Warning

Rate limit exceeded

@sawka has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 43 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 390ae7a and a178ab2.

📒 Files selected for processing (3)
  • emain/emain-tabview.ts (4 hunks)
  • frontend/app/store/keymodel.ts (7 hunks)
  • frontend/util/sharedconst.ts (1 hunks)

Walkthrough

The changes add support for chorded keybindings by introducing a new component that renders sequential key combinations and updating the documentation to describe chord formatting and execution timing. A new method for managing keyboard chord states is implemented, allowing for enhanced keyboard event handling. Additionally, new IPC handlers are introduced to enable screenshot capture and to control the keyboard chord mode from the main process, with corresponding methods exposed through the preload API. Other modifications include code simplification in component rendering, the addition of a function to retrieve the focused block ID, and improvements to utility functions that convert keyboard events to descriptive strings. The changes span both frontend and backend parts of the application, integrating new functionality and refining existing event handling behaviors.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
emain/emain-tabview.ts (1)

96-110: Consider adding error handling for edge cases.

While the implementation is solid, consider handling these edge cases:

  1. Multiple rapid calls to setKeyboardChordMode(true)
  2. Potential memory leaks if component is destroyed while timeout is pending
 setKeyboardChordMode(mode: boolean) {
     this.keyboardChordMode = mode;
     if (mode) {
         if (this.resetChordModeTimeout) {
             clearTimeout(this.resetChordModeTimeout);
+            this.resetChordModeTimeout = null;
         }
         this.resetChordModeTimeout = setTimeout(() => {
             this.keyboardChordMode = false;
+            this.resetChordModeTimeout = null;
         }, 2000);
     } else {
         if (this.resetChordModeTimeout) {
             clearTimeout(this.resetChordModeTimeout);
+            this.resetChordModeTimeout = null;
         }
     }
 }
frontend/app/store/keymodel.ts (2)

36-41: Consider adding documentation for chord state management.

The chord-related variables would benefit from JSDoc comments explaining:

  • Purpose and structure of globalChordMap
  • Lifecycle of activeChord and chordTimeout
+/** Map storing chord key combinations and their associated handlers */
 const globalChordMap = new Map<string, Map<string, KeyHandler>>();

+/** Current active chord key combination */
 let activeChord: string | null = null;
+/** Timeout for resetting the active chord state */
 let chordTimeout: NodeJS.Timeout = null;

42-56: Consider adding error handling for edge cases.

The chord management functions should handle edge cases:

  1. Multiple rapid chord attempts
  2. Concurrent timeouts
 function resetChord() {
+    // Clear any existing chord state
     activeChord = null;
     if (chordTimeout) {
         clearTimeout(chordTimeout);
         chordTimeout = null;
     }
 }

 function setActiveChord(activeChordArg: string) {
+    if (!activeChordArg) {
+        return;
+    }
     if (chordTimeout) {
         clearTimeout(chordTimeout);
     }
     activeChord = activeChordArg;
     chordTimeout = setTimeout(() => resetChord(), 2000);
 }
docs/docs/keybindings.mdx (1)

18-18: Enhance chord documentation with examples and timeout behavior.

The chord timing documentation is clear but could be more helpful with additional details:

  • Add an example of a chord sequence (e.g., "For example, to split a block above, press Ctrl+Shift+s followed by ArrowUp within 2 seconds")
  • Explain what happens if the second key is not pressed within 2 seconds
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef30221 and 3cdd08d.

📒 Files selected for processing (11)
  • docs/docs/keybindings.mdx (2 hunks)
  • docs/src/components/kbd.tsx (1 hunks)
  • emain/emain-tabview.ts (3 hunks)
  • emain/emain.ts (2 hunks)
  • emain/preload.ts (2 hunks)
  • frontend/app/block/blockframe.tsx (1 hunks)
  • frontend/app/store/global.ts (1 hunks)
  • frontend/app/store/keymodel.ts (7 hunks)
  • frontend/app/view/launcher/launcher.tsx (1 hunks)
  • frontend/types/custom.d.ts (1 hunks)
  • frontend/util/keyutil.ts (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/app/view/launcher/launcher.tsx
  • frontend/app/block/blockframe.tsx
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build Docsite
  • GitHub Check: Analyze (go)
  • GitHub Check: merge-gatekeeper
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (13)
docs/src/components/kbd.tsx (1)

65-75: LGTM! Well-structured component for displaying keyboard chords.

The implementation is clean and handles key combinations effectively with proper visual separation and browser-only rendering.

emain/preload.ts (1)

54-55: LGTM! Clean IPC method exposure.

The methods are properly exposed with appropriate IPC patterns - invoke for captureScreenshot to handle async response and send for setKeyboardChordMode.

emain/emain-tabview.ts (2)

48-49: LGTM! Clear property declarations.

Properties are well-typed and properly initialized.


241-245: LGTM! Proper event handling for chord mode.

The event handler correctly prevents default behavior and reinjects the key event.

frontend/util/keyutil.ts (2)

34-61: LGTM! Comprehensive key description generator.

The function handles all cases effectively:

  • All modifier keys (Cmd, Option, Meta, Ctrl, Shift)
  • Special case for space character
  • Fallback to code when key is empty

215-215: LGTM! Added null safety check.

Good defensive programming by adding the null check before accessing eventKey.

frontend/types/custom.d.ts (1)

104-105: Verify the purpose of these API additions.

The new methods seem to serve different purposes:

  1. captureScreenshot appears unrelated to the PR objectives of keyboard chord support and block splitting.
  2. setKeyboardChordMode aligns with the keyboard chord support objective.

Could you clarify if the screenshot functionality is intentionally included in this PR or if it should be moved to a separate PR focused on screenshot features?

frontend/app/store/keymodel.ts (3)

32-32: LGTM! Well-defined type for keyboard handlers.

The KeyHandler type clearly defines the expected signature for keyboard event handlers.


521-538: LGTM! Well-structured split block key mappings.

The split block key mappings are logically organized and provide intuitive directional controls:

  • ArrowUp: Split vertically before
  • ArrowDown: Split vertically after
  • ArrowLeft: Split horizontally before
  • ArrowRight: Split horizontally after

443-454: LGTM! Clear block functionality.

The Ctrl+Shift+k shortcut for replacing the focused block with a launcher view is well-implemented.

emain/emain.ts (1)

262-270: Verify if screenshot functionality belongs in this PR.

The screenshot capture functionality seems unrelated to the PR objectives of keyboard chord support and block manipulation.

Consider moving this feature to a separate PR focused on screenshot capabilities.

frontend/app/store/global.ts (1)

580-584: LGTM! Well-implemented focused block retrieval.

The getFocusedBlockId function is concise and effectively retrieves the currently focused block's ID, which is essential for block manipulation operations.

docs/docs/keybindings.mdx (1)

29-34: Clarify duplicate split functionality.

There are two different shortcuts for the same actions:

  • Vertical split below: Cmd+Shift+d and Ctrl+Shift+s ArrowDown
  • Horizontal split right: Cmd+d and Ctrl+Shift+s ArrowRight

Consider adding a note to explain why there are multiple ways to achieve the same result or if there are any subtle differences between them.

Comment on lines +325 to +329
electron.ipcMain.on("set-keyboard-chord-mode", (event) => {
event.returnValue = null;
const tabView = getWaveTabViewByWebContentsId(event.sender.id);
tabView?.setKeyboardChordMode(true);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for keyboard chord mode.

The keyboard chord mode handler should handle potential errors:

  1. Missing tab view
  2. Failed mode setting
 electron.ipcMain.on("set-keyboard-chord-mode", (event) => {
     event.returnValue = null;
     const tabView = getWaveTabViewByWebContentsId(event.sender.id);
+    if (!tabView) {
+        console.error("No tab view found for keyboard chord mode");
+        return;
+    }
     tabView?.setKeyboardChordMode(true);
+    console.log("Keyboard chord mode enabled for tab view");
 });

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
frontend/app/store/keymodel.ts (4)

32-37: Consider extracting chord configuration.

The chord implementation looks good, but consider extracting the timeout duration (2000ms) into a configuration constant for better maintainability.

+const CHORD_TIMEOUT_MS = 2000;
 type KeyHandler = (event: WaveKeyboardEvent) => boolean;

 const simpleControlShiftAtom = jotai.atom(false);
 const globalKeyMap = new Map<string, (waveEvent: WaveKeyboardEvent) => boolean>();
 const globalChordMap = new Map<string, Map<string, KeyHandler>>();

245-263: Consider reducing duplication in split functions.

The handleSplitHorizontal and handleSplitVertical functions share almost identical structure. Consider extracting the common logic into a shared helper function.

+async function handleSplit(
+    direction: "horizontal" | "vertical",
+    position: "before" | "after"
+) {
+    const layoutModel = getLayoutModelForStaticTab();
+    const focusedNode = globalStore.get(layoutModel.focusedNode);
+    if (focusedNode == null) {
+        return;
+    }
+    const blockDef = getDefaultNewBlockDef();
+    await (direction === "horizontal"
+        ? createBlockSplitHorizontally
+        : createBlockSplitVertically)(blockDef, focusedNode.data.blockId, position);
+}
+
-async function handleSplitHorizontal(position: "before" | "after") {
-    const layoutModel = getLayoutModelForStaticTab();
-    const focusedNode = globalStore.get(layoutModel.focusedNode);
-    if (focusedNode == null) {
-        return;
-    }
-    const blockDef = getDefaultNewBlockDef();
-    await createBlockSplitHorizontally(blockDef, focusedNode.data.blockId, position);
+async function handleSplitHorizontal(position: "before" | "after") {
+    return handleSplit("horizontal", position);
 }

-async function handleSplitVertical(position: "before" | "after") {
-    const layoutModel = getLayoutModelForStaticTab();
-    const focusedNode = globalStore.get(layoutModel.focusedNode);
-    if (focusedNode == null) {
-        return;
-    }
-    const blockDef = getDefaultNewBlockDef();
-    await createBlockSplitVertically(blockDef, focusedNode.data.blockId, position);
+async function handleSplitVertical(position: "before" | "after") {
+    return handleSplit("vertical", position);
 }

281-281: Remove debug console.log statements.

These debug logs should be removed or replaced with proper logging utility for production code.

-        console.log("lastHandledEvent return false");
-        console.log("handle activeChord", activeChord);
+        // Consider using a logging utility if debugging is needed in production

Also applies to: 286-286


444-455: Reuse launcher block definition.

Consider reusing the launcher block definition from getDefaultNewBlockDef to maintain consistency and reduce duplication.

     globalKeyMap.set("Ctrl:Shift:k", () => {
         const blockId = getFocusedBlockId();
         if (blockId == null) {
             return true;
         }
-        replaceBlock(blockId, {
-            meta: {
-                view: "launcher",
-            },
-        });
+        const launcherDef = getDefaultNewBlockDef();
+        launcherDef.meta.view = "launcher";
+        replaceBlock(blockId, launcherDef);
         return true;
     });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3cdd08d and 2eab37f.

📒 Files selected for processing (1)
  • frontend/app/store/keymodel.ts (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (2)
frontend/app/store/keymodel.ts (2)

268-276: Well-designed key mapping utility!

The checkKeyMap function is well-implemented with:

  • Generic type support for flexible handler types
  • Clear tuple return type
  • Efficient key matching

522-539: Well-organized split block shortcuts!

The chord-based split block shortcuts are well-organized and provide intuitive directional controls.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
emain/emain-tabview.ts (2)

96-111: Consider improvements to the keyboard chord mode implementation.

While the implementation is functional, consider these enhancements:

  1. Extract the timeout duration (2000ms) to a named constant for better maintainability
  2. Simplify the timeout cleanup in the 'else' block
  3. Add JSDoc documentation to describe the method's purpose and parameters

Apply this diff to implement the suggested improvements:

+const KEYBOARD_CHORD_MODE_TIMEOUT_MS = 2000;
+
+/**
+ * Sets the keyboard chord mode state and manages its auto-reset timeout.
+ * @param mode - When true, enables chord mode and sets a timeout to disable it.
+ *               When false, immediately disables chord mode and cleans up the timeout.
+ */
 setKeyboardChordMode(mode: boolean) {
     this.keyboardChordMode = mode;
     if (mode) {
         if (this.resetChordModeTimeout) {
             clearTimeout(this.resetChordModeTimeout);
         }
         this.resetChordModeTimeout = setTimeout(() => {
             this.keyboardChordMode = false;
-        }, 2000);
+        }, KEYBOARD_CHORD_MODE_TIMEOUT_MS);
     } else {
-        if (this.resetChordModeTimeout) {
-            clearTimeout(this.resetChordModeTimeout);
-            this.resetChordModeTimeout = null;
-        }
+        clearTimeout(this.resetChordModeTimeout);
+        this.resetChordModeTimeout = null;
     }
 }

242-246: Add documentation for keyboard chord mode handling.

The implementation correctly handles keyboard events in chord mode, but would benefit from documentation explaining the behavior.

Add a comment to explain the chord mode handling:

+        // In chord mode, prevent the default key behavior, disable chord mode,
+        // and reinject the key event to be handled by the renderer process
         if (input.type == "keyDown" && tabView.keyboardChordMode) {
             e.preventDefault();
             tabView.setKeyboardChordMode(false);
             tabView.webContents.send("reinject-key", waveEvent);
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e018858 and 390ae7a.

📒 Files selected for processing (1)
  • emain/emain-tabview.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build for TestDriver.ai
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
emain/emain-tabview.ts (1)

48-49: LGTM! Properties are well-typed and properly initialized.

The new properties keyboardChordMode and resetChordModeTimeout are appropriately typed and initialized for managing keyboard chord state.

@sawka sawka merged commit e126463 into main Feb 14, 2025
9 of 10 checks passed
@sawka sawka deleted the sawka/wavespace-lite branch February 14, 2025 21:25
xxyy2024 pushed a commit to xxyy2024/waveterm_aipy that referenced this pull request Jun 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant